package Test;

import java.util.concurrent.*;

public class CustomThreadPool {
    public static ExecutorService getThreadPool() {

        int corePoolSize = Runtime.getRuntime().availableProcessors() + 1;
        int maximumPoolSize = Runtime.getRuntime().availableProcessors() * 2;
        long keepAliveTime = 60L; // 非核心线程空闲1分钟后销毁
        TimeUnit unit = TimeUnit.SECONDS;

        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1000);
        // 线程工厂：自定义线程名，便于排查
        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 0;
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, "custom-thread-" + count++);
                thread.setDaemon(false); // 非守护线程
                return thread;
            }
        };

        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

        return new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            unit,
            workQueue,
            threadFactory,
            handler
        );
    }
}